import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 提供初始用户对象，避免null导致的错误
    user: {
      id: 0,
      username: 'guest',
      email: 'guest@example.com',
      role: '访客',
      isActive: true,
      createdAt: new Date().toISOString()
    },
    isLoading: false,
    error: null
  }),
  
  getters: {
    userFormattedDate: (state) => {
      if (!state.user || !state.user.createdAt) return ''
      return new Date(state.user.createdAt).toLocaleDateString()
    }
  },
  
  actions: {
    async login(username, password) {
      this.isLoading = true
      this.error = null
      
      try {
        // 模拟 API 调用
        await new Promise(resolve => setTimeout(resolve, 800))
        
        // 模拟验证
        if (username === 'admin' || username === 'user') {
          this.user = {
            id: 1,
            username,
            email: `${username}@example.com`,
            role: username === 'admin' ? '管理员' : '用户',
            isActive: true,
            createdAt: '2023-01-01T00:00:00Z'
          }
        } else {
          throw new Error('用户名或密码错误')
        }
      } catch (err) {
        this.error = err.message
      } finally {
        this.isLoading = false
      }
    },
    logout() {
      this.user = null
    }
  }
})